<?php
	///////////////////////////////////////////////////////////////////////////////////////////////////
	//	PHP INCLUDES
	//	WRITTEN BY: TRAVIS THORNTON
	//	12-07-2009
	//
	//	What this page does:
	//	1) Function for checking if the user is logged on
	//	2) Function to make sure the user is a manager
	//	3) Functions to encapsulate mysql connection, selection, query and close
	//	4) Header function - alters the header depending on the user status (guest, user, manager)
	//	5) Logging function. Will get called whenever the sqlQuery function is used, or can be called for logon, logoff
	//
	////////////////////////////////////////////////////////////////////////////////////////////////////
require_once "admin_options.php";

//global for mysql connection
$conn;

//checks if user is logged on, if not it errors
//This all checks session timeout
function checkLogin()
{
	//use global admin variable
	global $admin_session_time;
	
	//if session is timed out
	if ($_SESSION['sessionStartTime'] + $admin_session_time < time() )    //If the session is expired
	{
		session_destroy();//kill it
		session_start();//restart
	}
	else
	{	
		//refresh time
		$_SESSION['sessionStartTime'] = time();
	}
	
	//if user is false	
	if (isset($_SESSION['tmsUserID']) == FALSE)
	{
		//error
		$_SESSION['errorMessage'] = "You are not logged on.<br>Click <a href=\"main.php\">here</a> to log in";
		include("error.php");
		exit();
	}	
}

//Check if it is a manager
//used by manager only pages
function checkManager()
{
	if((isset($_SESSION['tmsUserType']) == FALSE) || ($_SESSION['tmsUserType'] != 1))
	{
		//error
		$_SESSION['errorMessage'] = "Access denied";
		include("error.php");
		exit();
	}
}

//connect to dbserver and select db	
function sqlConnect()
{
	//use globals
	global $dbhost;
	global $dbuser;
	global $dbpass;
	global $dbname;
	global $conn;
		
	//connect
	$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
	
	//select the correct db
	mysql_select_db($dbname);
}

//query function	
function sqlQuery($statement)
{
	// Perform Query
	$result = mysql_query($statement);

	// Check result
	if (!$result) 
	{
		$message  = 'Invalid query: ' . mysql_error() . "<br>\n";
		$message .= 'Whole query: ' . $statement;
		die($message);
	}
	
	//log the statement
	logDB($statement);

	//return query results
	return $result;
}

//same as above, but does not log the query
//used for admin functions that don't need to be logged
function sqlQueryNoLog($statement)
{
	// Perform Query
	$result = mysql_query($statement);

	// Check result
	if (!$result) 
	{
		$message  = 'Invalid query: ' . mysql_error() . "<br>\n";
		$message .= 'Whole query: ' . $statement;
		die($message);
	}
	
	//return result
	return $result;
}
	
//closes mysql connection
function sqlExit()
{
	//use global
	global $conn;
	
	//close connection
	mysql_close($conn);
}

//logs to the db
function logDB($input)
{
	//use globals
	global $log_selects;
	global $dbhost;
	global $dbuser;
	global $dbpass;
	global $dbname;
	
	//format the input
	$input = str_replace(";", "", $input);
	$input = addslashes($input);
	
	//events:
	// 0 login
	// 1 logout
	// 2 select
	// 3 insert
	// 4 update
	// 5 delete
	// 6 unknown
	$event_data = explode(" ", strtoupper($input));//make it into an array instead of substringing it
	$event = 6;
	
	//determine what the query or event is and set an event int
	switch($event_data[0])
	{
		case 'LOGIN':
			$event = 0;
		break;
		case 'LOGOUT':
			$event = 1;
		break;
		case 'SELECT':
			$event = 2;
		break;
		case 'INSERT':
			$event = 3;
		break;
		case 'UPDATE':
			$event = 4;
		break;
		case 'DELETE':
			$event = 5;
		break;
		default:
			$event = 6;
	}
	
	//determine if we need to log selects
	if($log_selects == 1 || ($log_selects == 0 && $event != 2))
	{
		//auto user = guest - this is why user is not a foreign key
		$user = "Guest";
		
		//set to user if logged on
		if(isset($_SESSION['tmsUserID']) == TRUE)
		{
			$user = $_SESSION['tmsUserID'];
		}
		
		//insert into the table
		//inserting the calling page and the user's ip address for security
		$sql = 'INSERT INTO `' . $dbname . '`.`DBLog` (`LogEntry`, `User`, `IP`, `CallingPage`, `EventTime`, `Event`, `Description`) VALUES (NULL, \''. $user . '\', \'' . $_SERVER['REMOTE_ADDR'] .'\', \'' . $_SERVER["SCRIPT_NAME"] .'\', CURRENT_TIMESTAMP, \'' . $event . '\', \'' . $input . '\');';			
		
		//Don't log it or else it will be infinite 
		sqlConnect();
		$results = sqlQueryNoLog($sql);
		sqlExit();
	}
}

//write the header
function writeHeader()
{
	require 'admin_options.php';
	
	//show the logo
	echo "<div class=\"logo\">\n";
	echo "	<img src=\"";
	echo $header_image;
	echo "\" alt=\"";
	echo $header_image_alt;
	echo "\" />\n";
	echo "</div>\n";
	
	//determine if logged on
	if( isset($_SESSION['tmsUserID']) )
	{
		sqlConnect();		
		$sql = 'select EmployeeFName, EmployeeLName, EmployeeID from Employee where EmployeeID = \'' . $_SESSION['tmsUserID'] . '\''; 
			
		// Perform Query
		$sqlresult = sqlQuery($sql);

		//get user info to display
		$fname = mysql_result($sqlresult, 0, 0);
		$lname = mysql_result($sqlresult, 0, 1);
		$userid = mysql_result($sqlresult, 0, 2);
		
		//display user info
		echo "<div class=\"user_logged\">";
		echo "Logged in as " . $fname. " " . $lname . "(" . $_SESSION['tmsUserID'] . ")<br/>";
		echo "</div>";
		
		//<!-- basic user links-->
		echo "<div class=\"user_links\">";
		echo "	<a href=\"main.php\">Main Page</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
		echo "	<a href=\"timesheet.php\">My Current Timesheet</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
		echo "	<a href=\"previoustime.php\">My Timesheets</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
		echo "	<a href=\"search.php\">Find Employee</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
		echo "	<a href=\"controlpanel.php\">Control Panel</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
		echo "	<a href=\"signout.php\">Signout</a>";
		echo "</div>";
		
		//if manager
		if( $_SESSION['tmsUserType'] == 1 )
		{
			//<!-- only visible if logged in with manager -->
			//get count of pending errors
			$sql = 'select COUNT(*) from ReportedErrors, Employee where ReportedErrors.EmployeeID = Employee.EmployeeID AND Employee.ManagerID = \'' . $_SESSION['tmsUserID'] . '\''; 
			
			// Perform Query
			$sqlresult = sqlQuery($sql);
			$numerrors = mysql_result($sqlresult, 0, 0);
			
			//get number of pending approvals
			$sql = 'select COUNT(*) from PayPeriod, Employee where PayPeriod.EmployeeID = Employee.EmployeeID AND PayPeriod.PeriodStatus = 1 AND Employee.ManagerID = \'' . $_SESSION['tmsUserID'] . '\''; 
			
			// Perform Query
			$sqlresult = sqlQuery($sql);
			$numpending = mysql_result($sqlresult, 0, 0);
		
			echo "<div class=\"manager\">";
			echo "	<a href=\"search_results.php?my_employees\">My Employees</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
			echo "	<a href=\"addemployee.php\">Add Employee</a> &nbsp;&nbsp;|&nbsp;&nbsp;";
            echo "  <a href=\"changeManager.php\">Move Employee</a> &nbsp;&nbsp;|&nbsp;&nbsp;";//Added by: Muenge
            echo "  <a href=\"managerMessage.php\">Change Welcome Message</a> &nbsp;&nbsp;|&nbsp;&nbsp;";//Added by: Muenge
			echo "	<a href=\"errorsreported.php\">Errors Reported</a>";
			
			//only show if needed
			if( $numerrors > 0 )
			{
				echo " <span class=\"error_cnt\">(" . $numerrors . ")</span>";
			}
			
			echo " &nbsp;&nbsp;|&nbsp;&nbsp;";
			echo "	<a href=\"submittedtime.php\">Submitted Timesheets</a>";
			
			//only show if needed
			if( $numpending > 0 )
			{
				echo " <span class=\"error_cnt\">(" . $numpending . ")</span>";
			}
			
			echo " &nbsp;&nbsp;|&nbsp;&nbsp;";
			echo "	<a href=\"reports.php\">Timesheet Reports</a>";
			echo "</div>";
		}
		
		echo "<div class=\"back_button_warn\" align=\"center\">";
		echo "WARNING: DO NOT USE THE BROWSER'S BUTTONS FOR NAVIGATION!<br/>";//need this because there is a lot of form input back and forth
		echo "</div>";
		
		sqlExit();
	}
}
?>